package com.baidu.udpDemo1;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws Exception {
        //1.创建DatagramSocket 可以指定访问服务端的端口号 (扔消息的人)
        DatagramSocket datagramSocket = new DatagramSocket(6668);

        //2.创建扔消息的数据包 及消息
        //2.1.创建扫描器监控输入消息
        Scanner scanner = new Scanner(System.in);

        //2.2.循环读取消息并分别发送
        while (true) {
            System.out.println("请输入:");
            String msg = scanner.next();

            if("exit".equals(msg)){
                datagramSocket.close();
                break;
            }

            byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);

            //2.3.创建数据包
            //(byte buf[], int offset, int length, InetAddress address, int port
            DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, InetAddress.getLocalHost(), 9999);

            //2.4.发送数据包
            datagramSocket.send(datagramPacket);
        }
    }
}
